# 葵崽管理器自动打包脚本
# 功能：自动检测并安装依赖，打包Python程序为exe

#Requires -RunAsAdministrator

# 设置控制台编码
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8
chcp 65001 | Out-Null

# 配置
$scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path
$pythonScript = Join-Path $scriptPath "yunzai_manager.py"
$outputName = "葵崽专属管理器"
$iconPath = Join-Path $scriptPath "icon.ico"
$requirementsFile = Join-Path $scriptPath "requirements.txt"

# 输出函数
function Write-ColoredOutput {
    param(
        [string]$Message,
        [string]$Color = "White"
    )
    Write-Host $Message -ForegroundColor $Color
}

# 检查Python是否安装
function Test-Python {
    try {
        $pythonVersion = & python --version 2>&1
        if ($pythonVersion -match "Python (\d+\.\d+)") {
            $version = [version]$matches[1]
            if ($version -ge [version]"3.8") {
                Write-ColoredOutput "✓ Python $version 已安装" "Green"
                return $true
            } else {
                Write-ColoredOutput "✗ Python版本过低，需要3.8或更高版本" "Red"
                return $false
            }
        }
    } catch {
        Write-ColoredOutput "✗ Python未安装" "Red"
        return $false
    }
}

# 创建requirements.txt
function Create-Requirements {
    $requirements = @"
customtkinter>=5.2.0
Pillow>=10.0.0
requests>=2.31.0
pyinstaller>=6.0.0
"@
    
    $requirements | Out-File -FilePath $requirementsFile -Encoding UTF8
    Write-ColoredOutput "✓ 创建 requirements.txt" "Green"
}

# 创建虚拟环境
function Create-VirtualEnv {
    Write-ColoredOutput "`n创建虚拟环境..." "Cyan"
    
    $venvPath = Join-Path $scriptPath "venv"
    
    if (Test-Path $venvPath) {
        Write-ColoredOutput "虚拟环境已存在，是否重新创建？(Y/N)" "Yellow"
        $response = Read-Host
        if ($response -eq 'Y' -or $response -eq 'y') {
            Remove-Item -Path $venvPath -Recurse -Force
        } else {
            return $venvPath
        }
    }
    
    & python -m venv $venvPath
    if ($LASTEXITCODE -eq 0) {
        Write-ColoredOutput "✓ 虚拟环境创建成功" "Green"
        return $venvPath
    } else {
        Write-ColoredOutput "✗ 虚拟环境创建失败" "Red"
        return $null
    }
}

# 安装依赖
function Install-Dependencies {
    param([string]$venvPath)
    
    Write-ColoredOutput "`n安装依赖包..." "Cyan"
    
    $pipPath = Join-Path $venvPath "Scripts\pip.exe"
    $pythonPath = Join-Path $venvPath "Scripts\python.exe"
    
    # 升级pip
    Write-ColoredOutput "升级pip..." "Gray"
    & $pythonPath -m pip install --upgrade pip
    
    # 安装依赖
    Write-ColoredOutput "安装项目依赖..." "Gray"
    & $pipPath install -r $requirementsFile --index-url https://pypi.org/simple --trusted-host pypi.org
    
    if ($LASTEXITCODE -eq 0) {
        Write-ColoredOutput "✓ 依赖安装成功" "Green"
        return $true
    } else {
        Write-ColoredOutput "✗ 依赖安装失败" "Red"
        return $false
    }
}

# 打包程序
function Build-Executable {
    param([string]$venvPath)
    
    Write-ColoredOutput "`n开始打包程序..." "Cyan"
    
    $pyinstallerPath = Join-Path $venvPath "Scripts\pyinstaller.exe"
    
    # 构建PyInstaller命令
    $buildArgs = @(
        "--onefile",
        "--windowed",
        "--name=$outputName",
        "--clean",
        "--noconfirm"
    )
    
    # 如果有图标文件
    if (Test-Path $iconPath) {
        $buildArgs += "--icon=$iconPath"
    }
    
    # 添加额外的隐藏导入
    $hiddenImports = @(
        "PIL._tkinter_finder",
        "customtkinter",
        "darkdetect",
        "packaging"
    )
    
    foreach ($import in $hiddenImports) {
        $buildArgs += "--hidden-import=$import"
    }
    
    # 添加数据文件（如果有）
    # $buildArgs += "--add-data=`"assets;assets`""
    
    # 执行打包
    Write-ColoredOutput "执行打包命令..." "Gray"
    & $pyinstallerPath $buildArgs $pythonScript
    
    if ($LASTEXITCODE -eq 0) {
        Write-ColoredOutput "✓ 打包成功" "Green"
        
        # 移动生成的exe到脚本目录
        $distPath = Join-Path $scriptPath "dist"
        $exePath = Join-Path $distPath "$outputName.exe"
        
        if (Test-Path $exePath) {
            $finalPath = Join-Path $scriptPath "$outputName.exe"
            Move-Item -Path $exePath -Destination $finalPath -Force
            Write-ColoredOutput "✓ 程序已生成: $finalPath" "Green"
            
            # 清理临时文件
            Remove-Item -Path $distPath -Recurse -Force -ErrorAction SilentlyContinue
            Remove-Item -Path (Join-Path $scriptPath "build") -Recurse -Force -ErrorAction SilentlyContinue
            Remove-Item -Path (Join-Path $scriptPath "*.spec") -Force -ErrorAction SilentlyContinue
            
            return $true
        }
    }
    
    Write-ColoredOutput "✗ 打包失败" "Red"
    return $false
}

# 主流程
function Main {
    Write-ColoredOutput "=====================================" "Cyan"
    Write-ColoredOutput "   葵崽管理器自动打包脚本" "Cyan"
    Write-ColoredOutput "=====================================" "Cyan"
    Write-ColoredOutput ""
    
    # 检查Python脚本是否存在
    if (-not (Test-Path $pythonScript)) {
        Write-ColoredOutput "✗ 找不到 yunzai_manager.py" "Red"
        Write-ColoredOutput "请确保脚本在正确的目录中" "Yellow"
        return
    }
    
    # 检查Python
    if (-not (Test-Python)) {
        Write-ColoredOutput "`n请先安装Python 3.8或更高版本" "Yellow"
        Write-ColoredOutput "下载地址: https://www.python.org/downloads/" "Yellow"
        return
    }
    
    # 创建requirements.txt
    Create-Requirements
    
    # 创建虚拟环境
    $venvPath = Create-VirtualEnv
    if (-not $venvPath) {
        return
    }
    
    # 安装依赖
    if (-not (Install-Dependencies -venvPath $venvPath)) {
        return
    }
    
    # 打包程序
    if (Build-Executable -venvPath $venvPath) {
        Write-ColoredOutput "`n=====================================" "Green"
        Write-ColoredOutput "   打包完成！" "Green"
        Write-ColoredOutput "=====================================" "Green"
        
        # 询问是否运行
        Write-ColoredOutput "`n是否立即运行程序？(Y/N)" "Yellow"
        $response = Read-Host
        if ($response -eq 'Y' -or $response -eq 'y') {
            $exePath = Join-Path $scriptPath "$outputName.exe"
            Start-Process -FilePath $exePath
        }
    }
}

# 运行主流程
try {
    Main
} catch {
    Write-ColoredOutput "`n发生错误: $_" "Red"
} finally {
    Write-ColoredOutput "`n按任意键退出..." "Gray"
    $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}